import os

def rename_images():
    # 获取当前文件夹路径
    folder_path = input("请输入要处理的文件夹路径: ")
    # 存储已存在的文件名编号
    existing_numbers = set()
    max_number = 0

    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            try:
                # 提取文件名中的数字部分
                number = int(os.path.splitext(filename)[0])
                existing_numbers.add(number)
                if number > max_number:
                    max_number = number
            except ValueError:
                # 文件名不是纯数字，跳过
                continue

    # 从最大数字加 1 开始重新编号
    next_number = max_number + 1
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            try:
                # 尝试提取文件名中的数字部分
                _ = int(os.path.splitext(filename)[0])
                # 如果文件名是纯数字，跳过
                continue
            except ValueError:
                # 文件名不是纯数字，需要重命名
                while next_number in existing_numbers:
                    next_number += 1
                # 获取文件扩展名
                ext = os.path.splitext(filename)[1]
                new_name = f"{next_number}{ext}"
                old_path = os.path.join(folder_path, filename)
                new_path = os.path.join(folder_path, new_name)
                os.rename(old_path, new_path)
                print(f"Renamed {filename} to {new_name}")
                existing_numbers.add(next_number)
                next_number += 1

if __name__ == "__main__":
    rename_images()
